﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Nuanyang.Asp.Net.Core.Extension.DataBase;
using Nuanyang.Asp.Net.Core.Extension.Middleware;
using Serilog;

namespace Nuanyang.Asp.Net.Core.Extension
{
    public static class ApplicationExtension
    {
        /// <summary>
        /// 使用权限过滤
        /// </summary>
        /// <param name="applicationBuilder"></param>
        /// <param name="action"></param>
        /// <param name="claimName">gourpId 所在claim Name</param>
        /// <returns></returns>
        public static IApplicationBuilder UsePermission(this IApplicationBuilder applicationBuilder, string claimName = "role")
        {
            return applicationBuilder.UseMiddleware<PermissionMiddleware>(applicationBuilder.ApplicationServices.GetService(typeof(FunctionContext)), claimName);
        }

        /// <summary>
        /// 迁移function表
        /// </summary>
        /// <param name="applicationBuilder"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseFunction(this IApplicationBuilder applicationBuilder)
        {

            applicationBuilder.UseEndpoints(endpoints => endpoints.AddFunction(applicationBuilder.ApplicationServices.GetService(typeof(FunctionContext)) as FunctionContext));
            return applicationBuilder;
        }


        /// <summary>
        /// 使用异常处理
        /// </summary>
        /// <param name="applicationBuilder"></param>
        /// <param name="printInConsole">是否打印到控制台</param>
        /// <param name="logger">日志服务</param>
        /// <returns></returns>
        public static IApplicationBuilder UseApplicationErrorLog(this IApplicationBuilder applicationBuilder, bool printInConsole = true, ILogger logger = null)
        {
            if (logger == null)
            {
                logger = applicationBuilder.ApplicationServices.GetService(typeof(ILogger)) as ILogger;
            }
            return applicationBuilder.UseMiddleware<ExceptionMiddleware>(printInConsole, logger);
        }

        /// <summary>
        /// 使用请求记录功能
        /// </summary>
        /// <param name="applicationBuilder"></param>
        /// <param name="logger">日志服务</param>
        /// <returns></returns>
        public static IApplicationBuilder UseRequestLog(this IApplicationBuilder applicationBuilder, ILogger logger = null)
        {
            if (logger == null)
            {
                logger = applicationBuilder.ApplicationServices.GetService(typeof(ILogger)) as ILogger;
            }
            return applicationBuilder.UseMiddleware<RequestLogMiddleware>(applicationBuilder.ApplicationServices.GetService(typeof(ILogger)));
        }
    }
}
